# import win32api, win32con, win32gui
from base64 import encode
import uuid
from xmlrpc.client import boolean
import yaml
import os
import pyautogui
import time
import datetime  # 导入datetime模块
import threading  # 导入threading模块
from paddleocr import PaddleOCR
from PIL import Image
from PIL import ImageGrab
import cv2
import numpy as np
# 自写外部类
import count
import imgCompare

# 读取配置文件


def dict2namespace():
    with open('config.yml', 'r', encoding='utf-8') as f:
        data = yaml.load(f, Loader=yaml.FullLoader)
        return data

# 创建截图文件夹


def makdir(path):
    try:
        isExists = os.path.exists(path)
        # 判断是否存在文件夹
        if not isExists:
            # 不存在创建
            os.makedirs(path)
            print(path+'文件夹创建成功！')
    except Exception as e:
        print(e)

# 截图


def grab_screenshot_area(x, y):
    # print(os.getcwd())
    path = os.getcwd()
    makdir(path+'\\pics\\')
    area = (x, y, x+77, y+77)   # 这里是设置截图范围的区域
    shot = ImageGrab.grab(area)
    filename = path+'\\pics\\'+str(uuid.uuid1())+'.png'
    shot.save(filename)
    # print(filename)
    return filename


def grab_screenshot_area1(x, y, x2, y2):
    # print(os.getcwd())
    path = os.getcwd()
    makdir(path+'\\pics\\')
    area = (x, y, x2, y2)   # 这里是设置截图范围的区域
    shot = ImageGrab.grab(area)
    filename = path+'\\pics\\'+str(uuid.uuid1())+'.png'
    shot.save(filename)
    # print(filename)
    return filename

# 判断是否可突破


def isTupo(filename):

    image = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
    newfile = filename+'1.jpg'
    cv2.imwrite(newfile, image)
    # need to run only once to download and load model into memory
    ocr = PaddleOCR(use_angle_cls=True, lang="ch")
    result = ocr.ocr(newfile, cls=True)
    # reader = easyocr.Reader(['ch_sim'])
    # result = reader.readtext(newfile)
    # images=Image.open(filename )
    # vode=pytesseract.image_to_string (images ,lang='chi_sim')
    strs = str(result)
    # print(strs)
    # print(result)
    str1, str2, str3, str4, str5 = '突', '破', '境', '渡', '劫'
    ifOk = 0
    # if strs.find(str1)!= -1 or strs.find(str2)!= -1 or strs.find(str3)!= -1 or strs.find(str4)!= -1 or strs.find(str5)!= -1:

    if strs.find(str1) != -1 or strs.find(str2) != -1 or strs.find(str3) != -1 or strs.find(str4) != -1 or strs.find(str5) != -1:
        ifOk = 1
    os.remove(filename)
    os.remove(newfile)
    # if (ifOk==1):
    #     print('当前角色可以突破,开始进行突破')
    # else:
    #     print('当前角色不可以突破,下一个')
    return ifOk == 1

# 判断是否要确定突破


def compare2pics(target, source):
    # print("target:"+target)
    # print("source:"+source)
    img1 = cv2.imread(target)
    img2 = cv2.imread(source)
    hash1 = imgCompare.aHash(img1)
    hash2 = imgCompare.aHash(img2)
    n = imgCompare.cmpHash(hash1, hash2)
    os.remove(source) 
    # print("n > 0.9:"+str(n > 0.9))
    return n > 0.9


def compare2tupo(target, source):
    # print("target:"+target)
    # print("source:"+source)
    img1 = cv2.imread(target)
    img2 = cv2.imread(source)
    hash1 = imgCompare.aHash(img1)
    hash2 = imgCompare.aHash(img2)
    n = imgCompare.cmpHash(hash1, hash2)
    os.remove(source) 
    # print("n > 0.9:"+str(n > 0.9))
    return n > 0.7


def isConfirm(filename):
    # 截图比对一下是不是需要按确定按钮
    configs = dict2namespace()
    path = os.getcwd()
    x, y, x2, y2 = configs['location']['jietu']['confrim']['x'], configs['location']['jietu']['confrim'][
        'y'], configs['location']['jietu']['confrim']['x2'], configs['location']['jietu']['confrim']['y2']
    area = (x, y, x2, y2)
    shot = ImageGrab.grab(area)
    filename = path+'\\pics\\'+str(uuid.uuid1())+'.png'
    shot.save(filename)
    result = compare2pics('target\\queding.png', filename)
    # os.remove(filename)
    # reader = easyocr.Reader(['ch_sim'])
    # result = reader.readtext(filename)
    # images=Image.open(filename )
    # vode=pytesseract.image_to_string (images ,lang='chi_sim')
    # strs = str(result)
    # # print(strs)
    # boolb = strs.__contains__('确定')
    return result


def getName(filename):
    # need to run only once to download and load model into memory
    ocr = PaddleOCR(use_angle_cls=True, lang="ch")
# result = ocr.ocr('pics\\1.png', cls=True)
    result = ocr.ocr(filename, cls=True)
    name = ''
    for line in result:
        for item in line:
            name += (item[1][0])
    os.remove(filename)
    return name


def doTupo(configs):
    # 获取突破按钮的截图(查看是否有丹炉图标，如果没有表示可以突破)
    hasDanlu = grab_screenshot_area1(
        configs['location']['jietu']['danlu']['x'], configs['location']['jietu']['danlu']['y'], configs['location']['jietu']['danlu']['x2'], configs['location']['jietu']['danlu']['y2'])
    # 判断是否可以突破
    # canTupo = isTupo(screenPicPath)
    # print(canTupo)

    if compare2tupo('target\\empty.png', hasDanlu)==True:
        # 如果可以突破
        # 识别人名
        x, y, x2, y2 = configs['location']['jietu']['name']['x'], configs['location']['jietu']['name'][
            'y'], configs['location']['jietu']['name']['x2'], configs['location']['jietu']['name']['y2']
        nameFile = grab_screenshot_area1(x, y, x2, y2)
        name = getName(nameFile)
        x, y, x2, y2 = configs['location']['jietu']['jingjie']['x'], configs['location']['jietu']['jingjie'][
            'y'], configs['location']['jietu']['jingjie']['x2'], configs['location']['jietu']['jingjie']['y2']
        jingjieFile = grab_screenshot_area1(x, y, x2, y2)
        jingjie = getName(jingjieFile)

        # 查看是否轮回者，非轮回者不吃药
        # x, y, x2, y2 = configs['location']['jietu']['pinji']['x'], configs['location']['jietu']['pinji'][
        #     'y'], configs['location']['jietu']['pinji']['x2'], configs['location']['jietu']['pinji']['y2']
        # pinjiFile = grab_screenshot_area1(x, y, x2, y2) 
        # if compare2pics('target\\lunhui.png', pinjiFile)==True:
            # 移动到吃丹药那个加号
            # pyautogui.moveTo(configs['location']['btn']['danyao']
            #                  ['x'], configs['location']['btn']['danyao']['y'])
            # # 打开丹药列表
            # pyautogui.click()

            # # 查看是否有突破药
            # x, y, x2, y2 = configs['location']['jietu']['use']['x'], configs['location']['jietu']['use'][
            # 'y'], configs['location']['jietu']['use']['x2'], configs['location']['jietu']['use']['y2']
            # useFile = grab_screenshot_area1(x, y, x2, y2)
            # if compare2pics('target\\useless.png', useFile)==True:
            #     #如果没有突破药 移动到丹药右边的使用按钮
            #     pyautogui.moveTo(configs['location']['btn']['next']
            #                  ['x'], configs['location']['btn']['next']['y'])
            #     pyautogui.click()
            #     time.sleep(2)
            
            # else:
            # # 移动到丹药右边的使用按钮
            #     pyautogui.moveTo(configs['location']['btn']['shiyong']
            #                  ['x'], configs['location']['btn']['shiyong']['y'])
            # # 使用突破药
            #     pyautogui.click()



        # 截图看一下要不要确认突破
        # x, y, x2, y2 = configs['location']['jietu']['queren']['x'], configs['location']['jietu']['queren'][
        #     'y'], configs['location']['jietu']['queren']['x2'], configs['location']['jietu']['queren']['y2']
        # querenPath =  grab_screenshot_area1(x, y, x2, y2)
        # # confirm = isConfirm(querenPath)
        # if compare2pics('target\\queren.png', querenPath)==True:
            # 移动到确认按钮
        # pyautogui.moveTo(configs['location']['btn']['queren']
        #                      ['x'], configs['location']['btn']['queren']['y'])
            # 点击确认
            # os.remove(querenPath)
        # 休眠,等待突破过场动画执行完毕
        # time.sleep(8)

        # 判断突破结果

        # 点击突破
        # 移动到突破按钮
        pyautogui.moveTo(configs['location']['btn']['tupo']
                         ['x'], configs['location']['btn']['tupo']['y'])
        pyautogui.click()
        # 移动到破镜|突破|渡劫 按钮
        pyautogui.moveTo(configs['location']['btn']['pojing']
                         ['x'], configs['location']['btn']['pojing']['y'])
        # 点击突破按钮
        pyautogui.click()
        # 等待加载突破动画
        time.sleep(1)
        # 跳过动画
        pyautogui.click()
        x, y, x2, y2 = configs['location']['jietu']['tuporesult']['x'], configs['location']['jietu']['tuporesult'][
            'y'], configs['location']['jietu']['tuporesult']['x2'], configs['location']['jietu']['tuporesult']['y2']
        resultFile = grab_screenshot_area1(x, y, x2, y2)
        if compare2pics('target\\success.png', resultFile):
                print(name+","+jingjie+"突破成功！")
                count.success += 1
        else:
                print(name+","+jingjie+"突破失败！")
                count.failed += 1
        # os.remove(resultFile)
        # 移动到向右的箭头,进行下一个
        pyautogui.moveTo(configs['location']['btn']['next']
                         ['x'], configs['location']['btn']['next']['y'])
        # 点击结束突破的动画
        pyautogui.click()
        time.sleep(0.5)
        # 点击关闭突破结果页
        pyautogui.click()
        time.sleep(0.5)
        # 点击进入下一个
        pyautogui.click()
        time.sleep(0.5)

    else:
        # 无法突破的话 直接进入下一个
        time.sleep(1)
        pyautogui.moveTo(configs['location']['btn']['next']
                         ['x'], configs['location']['btn']['next']['y'])
        pyautogui.click()
        currentMouseX, currentMouseY = pyautogui.position()  # 鼠标当前位置
        # print(currentMouseX, currentMouseY)
        time.sleep(1)


def job():  # 定义方法
    # 重置计数器
    count.success = 0
    count.failed = 0
    # 读取配置文件
    start_time = datetime.datetime.now()
    print('开始执行,当前时间为：'+str(start_time))

    # 进入修行页面-点击弟子按钮
    pyautogui.moveTo(configs['location']['btn']['dizi']
                     ['x'], configs['location']['btn']['dizi']['y'])
    pyautogui.click()
    time.sleep(1)

    # 进入修行页面-点击详情按钮
    pyautogui.moveTo(configs['location']['btn']['xiangqing']
                     ['x'], configs['location']['btn']['xiangqing']['y'])
    pyautogui.click()
    time.sleep(1)

    # 进入修行页面-点击修行按钮
    pyautogui.moveTo(configs['location']['btn']['xiuxing']
                     ['x'], configs['location']['btn']['xiuxing']['y'])
    pyautogui.click()
    time.sleep(1)
    for num in range(68):
        doTupo(configs)

    # 关闭人物列表
    pyautogui.moveTo(configs['location']['btn']['dizi']
                     ['x'], configs['location']['btn']['dizi']['y'])
    pyautogui.click()
    time.sleep(1)
    pyautogui.click()

    end_time = datetime.datetime.now()
    print('执行完毕,当前时间为：'+str(end_time))
    print('本次突破,共成功：'+str(count.success)+"个，失败"+str(count.failed)+"个")
    print('本次突破执行完毕,共耗时'+str((end_time-start_time).seconds) +
          '秒,'+str(configs['time'])+'分后再次执行')
    timer = threading.Timer(configs['time']*60, job)  # 每秒运行
    timer.start()  # 执行方法


if __name__ == "__main__":
    configs = dict2namespace()
    t1 = threading.Timer(1, function=job)  # 创建定时器
    t1.start()  # 开始执行线程
    # doTupo(configs)
